<?php
//过滤脚本代码
function cleanJs($text) {
	$text = trim ( $text );
	$text = stripslashes ( $text );
	//完全过滤注释
	$text = preg_replace ( '/<!--?.*-->/', '', $text );
	//完全过滤动态代码

	$text = preg_replace ( '/<\?|\?>/', '', $text );

	//完全过滤js
	$text = preg_replace ( '/<script?.*\/script>/', '', $text );
	//过滤多余html
	$text = preg_replace ( '/<\/?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset)[^><]*>/i', '', $text );
	//过滤on事件lang js
	while ( preg_match ( '/(<[^><]+)(lang|onfinish|onmouse|onexit|onerror|onclick|onkey|onload|onchange|onfocus|onblur)[^><]+/i', $text, $mat ) ) {
		$text = str_replace ( $mat [0], $mat [1], $text );
	}
	while ( preg_match ( '/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat ) ) {
		$text = str_replace ( $mat [0], $mat [1] . $mat [3], $text );
	}
	return $text;
}

//纯文本输入
function clearText($text) { 
	$text = cleanJs ( $text );
	//去除图片 视频 连接
	$text = preg_replace ( '/\[(图片)(\d+)\]/is', ' ', $text );
	$text = preg_replace ( '/\[(视频)(\d+)\]/is', ' ', $text );
	$text = preg_replace ( '/\[(url)([\s\S]*)\]([^\[]+)(\[\/url\])/is', ' ', $text );
	//彻底过滤空格BY xiomai
	$text = preg_replace ( '/\s(?=\s)/', '', $text );
	$text = preg_replace ( '/[\n\r\t]/', ' ', $text );
	$text = str_replace ( '  ', ' ', $text );
	$text = str_replace ( ' ', '', $text );
	$text = str_replace ( '&nbsp;', '', $text );
	$text = str_replace ( '&', '', $text );
	$text = str_replace ( '=', '', $text );
	$text = str_replace ( '-', '', $text );
	$text = str_replace ( '#', '', $text );
	$text = str_replace ( '%', '', $text );
	$text = str_replace ( '!', '', $text );
	$text = str_replace ( '@', '', $text );
	$text = str_replace ( '^', '', $text );
	$text = str_replace ( '*', '', $text );
	$text = str_replace ( 'amp;', '', $text );

	$text = strip_tags ( $text ); // 去除HTML、XML 以及 PHP 的标签
	$text = htmlspecialchars ( $text );
	$text = str_replace ( "'", "", $text );
	return $text;
}
/**
 * 获取和设置配置参数 支持批量定义
 * @param string|array $name 配置变量
 * @param mixed $value 配置值
 * @param mixed $default 默认值
 * @return mixed
 */
function C($name=null, $value=null,$default=null) {
    static $_config = array();
    // 无参数时获取所有
    if (empty($name)) {
        return $_config;
    }
    // 优先执行设置获取或赋值
    if (is_string($name)) {
        if (!strpos($name, '.')) {
            $name = strtoupper($name);
            if (is_null($value))
                return isset($_config[$name]) ? $_config[$name] : $default;
            $_config[$name] = $value;
            return;
        }
        // 二维数组设置和获取支持
        $name = explode('.', $name);
        $name[0]   =  strtoupper($name[0]);
        if (is_null($value))
            return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
        $_config[$name[0]][$name[1]] = $value;
        return;
    }
    // 批量设置
    if (is_array($name)){
        $_config = array_merge($_config, array_change_key_case($name,CASE_UPPER));
        return;
    }
    return null; // 避免非法参数
}
/**
 * M函数用于实例化一个没有模型文件的Model
 * @param string $name Model名称 支持指定基础模型 例如 ik_user 表对应模型 user
 * @return Model
 */
function M($name='') {
	$vimodel = new \IKPHP\Common\Models\VirtualModel();
	$vimodel->setviSource($name);
    return $vimodel;
}
/**
 * IKPHP 全站通用U函数处理url
 *
 *<code>
 *
 * //Generate a URL appending the URI to the base URI
 * echo U('products/edit/1');
 *
 * //Generate a URL for a predefined route
 * echo U(array('for' => 'blog-post', 'title' => 'some-cool-stuff', 'year' => '2012'));
 *
 *</code>
 *
 * @param string|array $uri
 * @param array|object args Optional arguments to be appended to the query string
 * @param bool|null $local
 * @return string
 */
function U($uri=null, $args=null){
	global $di;
	$url_obj = $di->getShared('url');
	if($url_obj){
		return $url_obj->get($uri, $args);
	}
	return null; 
}
/**
 * 获取输入参数 支持过滤和默认值
 * 使用方法:
 * <code>
 * I('id','trim'); 获取id参数 并用trim函数过滤
 * I('email','trim,email'); 获取id参数 并用trim,email函数过滤
 * I('email',array('trim','email')); 获取id参数 并用trim,email函数过滤
 * I('content','htmlspecialchars','ikphp wellcome here'); 
 * 获取content参数 并用htmlspecialchars函数过滤 如果不存在 使用默认值
 * </code>
 * @param string|array $data 要过滤的数据
 * @param string|array $filter 参数过滤方法 
 * @param mixed $default 不存在的时候默认值
 * @return mixed
 */
function I($data, $filter = null, $default='') {
	if(!empty($data)){
		//全局过滤检查
		$filters = isset($filter)?$filter:C('DEFAULT_FILTER');
		if($filters) {
		    if(is_string($filters)){
                $filters    =   explode(',',$filters);
            }elseif(is_int($filters)){
                $filters    =   array($filters);
            }
            
		    foreach($filters as $filter){
                if(function_exists($filter)) {
                    $data   =   is_array($data)?array_map_recursive($filter,$data):$filter($data); // 参数过滤
                }else{
                    $data   =   filter_var($data,is_int($filter)?$filter:filter_id($filter));
                    if(false === $data) {
                        return   isset($default)?$default:NULL;
                    }
                }
            } 
          
		}
	}else{
		// 变量默认值
        $data = isset($default)?$default:NULL;
    }
    
    return $data;
}
function array_map_recursive($filter, $data) {
     $result = array();
     foreach ($data as $key => $val) {
         $result[$key] = is_array($val)
             ? array_map_recursive($filter, $val)
             : call_user_func($filter, $val);
     }
     return $result;
}
/**
 * 获取用户头像
 */
function avatar($uid, $size, $face) {
	if(empty($face)){
		$ext = '.jpg';
	}else{
		$ext = '.'.fileext($face);
	}
    $avatar_size = explode(',', C('ik_avatar_size'));
    $size = in_array($size, $avatar_size) ? $size : '48';
    $avatar_dir = avatar_dir($uid); 
    $avatar_file = C('ik_attach_path') .'face/'.$avatar_dir.md5($uid).'_'.$size.'_'.$size.$ext; 
    if (!is_file($avatar_file)) {
    	$avatar_file = "user_48.jpg";
    	return C('ik_site_url') . 'static/images/' . $avatar_file.'?v='.time();
    }else{
    	return C('ik_site_url') .  $avatar_file.'?v='.time();
    }
    
}
function attach($attach) {
    if (false === strpos($attach, 'http://')) {
        //本地附件
        //判断是否存在 photo/1/2/533c32c3d3a4f_140_140.jpg
        $tempatt = C('ik_site_url').C('ik_attach_path').$attach;
        if(!is_file($tempatt)){
        	// TODO
        }
        return C('ik_site_url').C('ik_attach_path'). $attach.'?v='.time();
        //远程附件
        //todo...
    } else {
        //URL链接
        return $attach;
    }
}
function avatar_dir($uid) {
    $uid = abs(intval($uid));
    $suid = sprintf("%09d", $uid);
    $dir1 = substr($suid, 0, 3);
    $dir2 = substr($suid, 3, 2);
    $dir3 = substr($suid, 5, 2);
    return $dir1 . '/' . $dir2 . '/' . $dir3 . '/';
}
/**
 * 输入过滤函数
 * @param  string  $string 输入的字符串
 * @return string  转码后的安全串
 */
function shtmlspecialchars($string) {
	if (is_array ( $string )) {
		foreach ( $string as $key => $val ) {
			$string [$key] = shtmlspecialchars ( $val );
		}
	} else {
		$string = preg_replace ( '/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace ( array ('&', '"', '<', '>' ), array ('&amp;', '&quot;', '&lt;', '&gt;' ), $string ) );
	}
	return $string;
}
/**
 * 2014年3月19日 新增认证函数
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 * @author 小麦 <ikphp@sina.cn>
 */
function data_auth_sign($data) {
	//数据类型检测
	if (! is_array ( $data )) {
		$data = ( array ) $data;
	}
	ksort ( $data ); //排序
	$code = http_build_query ( $data ); //url编码并生成query字符串
	$sign = sha1 ( $code ); //生成签名
	return $sign;
}
//长度检查函数
function ck_strlen($string, $charset = 'utf8') {
	if (function_exists ( 'mb_strlen' )) {
		return mb_strlen ( $string, $charset );
	} else {
		return iconv_strlen ( $string, $charset );
	}
}
/*
* utf8字符串截取
* 用法：getsubstrutf8($string,5,20);
* @param $str string 需要截取的串
* @param $start intval 开始位置
* @param $sublen intval 要保留的字符长度
* @param $append boolean 是否要添加 ...
*/
function getsubstrutf8($string, $start = 0, $sublen, $append = true) {
	$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
	preg_match_all ( $pa, $string, $t_string );
	if (count ( $t_string [0] ) - $start > $sublen && $append == true) {
		return join ( '', array_slice ( $t_string [0], $start, $sublen ) ) . "...";
	} else {
		return join ( '', array_slice ( $t_string [0], $start, $sublen ) );
	}
}
/*
* 新增与2014年4月7日 修改人小麦
* IKPHP 专用文本输出截取字符串 弃用getsubstrutf8()函数
* 用法：sub_str(strip_tags($strNote["content"]),180); || sub_str($strNote["content"],180);
* @param $str string 需要截取的串
* @param $length intval 要保留的字符长度
* @param $append boolean 是否要添加 ...
* @param $charset string 'utf8' 文本编码格式
*/
function sub_str($str, $length = 0, $append = true, $charset = 'utf8') {
	$str = trim ( $str );
	$strlength = strlen ( $str );
	$charset = strtolower ( $charset );
	if ($charset == 'utf8') {
		$l = 0;
		$i = 0;
		while ( $i < $strlength ) {
			if (ord ( $str {$i} ) < 0x80) {
				$l ++;
				$i ++;
			} else if (ord ( $str {$i} ) < 0xe0) {
				$l ++;
				$i += 2;
			} else if (ord ( $str {$i} ) < 0xf0) {
				$l += 2;
				$i += 3;
			} else if (ord ( $str {$i} ) < 0xf8) {
				$l += 1;
				$i += 4;
			} else if (ord ( $str {$i} ) < 0xfc) {
				$l += 1;
				$i += 5;
			} else if (ord ( $str {$i} ) < 0xfe) {
				$l += 1;
				$i += 6;
			}
			if ($l >= $length) {
				$newstr = substr ( $str, 0, $i );
				break;
			}
		}
		if ($l < $length) {
			return $str;
		}
	} elseif ($charset == 'gbk') {
		if ($length == 0 || $length >= $strlength) {
			return $str;
		}
		while ( $i <= $strlength ) {
			if (ord ( $str {$i} ) > 0xa0) {
				$l += 2;
				$i += 2;
			} else {
				$l ++;
				$i ++;
			}
			if ($l >= $length) {
				$newstr = substr ( $str, 0, $i );
				break;
			}
		}
	}
	if ($append && $str != $newstr) {
		$newstr .= '..';
	}
	return $newstr;
}
/**
 * 使用正则验证数据
 * @access public
 * @param string $value  要验证的数据
 * @param string $rule 验证规则
 * @return boolean
 */
function regex($value,$rule) {
	$validate = array(
		'require'   =>  '/\S+/',
		'email'     =>  '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
		'url'       =>  '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
		'currency'  =>  '/^\d+(\.\d+)?$/',
		'number'    =>  '/^\d+$/',
		'zip'       =>  '/^\d{6}$/',
		'integer'   =>  '/^[-\+]?\d+$/',
		'double'    =>  '/^[-\+]?\d+(\.\d+)?$/',
		'english'   =>  '/^[A-Za-z]+$/',
	);
	// 检查是否有内置的正则表达式
	if(isset($validate[strtolower($rule)]))
		$rule       =   $validate[strtolower($rule)];
	return preg_match($rule,$value)===1;
}
//获取文件名后缀
function fileext($filename) {
	return strtolower(trim(substr(strrchr($filename, '.'), 1)));
}
/**
 * 获取文件名
 * @param string $filepath 源文件
 * **/
function filemain($filename) {
	return trim(substr($filename, 0, strrpos($filename, '.')));
}
/**
 * 抛出异常处理
 * @param string $msg 异常消息
 * @param integer $code 异常代码 默认为0
 * @return void
 */
function E($msg, $code=0) {
    throw new \Phalcon\Exception($msg, $code);
}
//生成随机数(1数字,0字母数字组合)
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand ( ( double ) microtime () * 1000000 ) : mt_srand ();
	$seed = base_convert ( md5 ( print_r ( $_SERVER, 1 ) . microtime () ), 16, $numeric ? 10 : 35 );
	$seed = $numeric ? (str_replace ( '0', '', $seed ) . '012340567890') : ($seed . 'zZ' . strtoupper ( $seed ));
	$hash = '';
	$max = strlen ( $seed ) - 1;
	for($i = 0; $i < $length; $i ++) {
		$hash .= $seed [mt_rand ( 0, $max )];
	}
	return $hash;
}
/**
 * 处理插件钩子
 * @param string $name   插件名称
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook($name,$hook,$params=array()){ 
	if(empty($name) || empty($hook)) return;
    $pluginObj = new \IKPHP\Plugins\BasePlugin($name);
    $plugin = $pluginObj->get($hook,$params);
	return $plugin;
}
/**
 * 处理内容文本中的图片
 * @param string $type     类型
 * @param string $typeid   类型ID
 * @param string $content  文本内容
 * @return void 纯文本
 */
function ikhtml_img($type,$typeid,$content){
	//图片
	$arr_photo = array();
	//匹配本地图片
	$strcontent = $content;	
	preg_match_all ( '/\[(图片)(\d+)\]/is', $strcontent, $photos ); 
	$images_mod = new IKPHP\Common\Models\Images();			
	foreach ($photos [2] as $key=>$item) {
		$strPhoto = $images_mod::getImageByseqid($type,$typeid,$item);
		if($strPhoto){
			$arr_photo[] = $strPhoto;
		}
		
	}	
	return $arr_photo;
}
/**
 * 处理内容文本输出过滤ik图片和视频
 * @param string $type     类型
 * @param string $typeid   类型ID
 * @param string $content  文本内容
 * @return void 纯文本
 */
function ikhtml_text($content){
	//图片
	$arr_photo = array();
	//匹配本地图片
	$strcontent = $content;	
	preg_match_all ( '/\[(图片)(\d+)\]/is', $strcontent, $photos ); 
	//$images_mod = new IKPHP\Common\Models\Images();			
	foreach ($photos [2] as $key=>$item) {
		//$strPhoto = $images_mod::getImageByseqid($type,$typeid,$item);
		$htmlTpl = '';
		$strcontent = str_replace ( '[图片'.$item.']', $htmlTpl, $strcontent );
	}
	//匹配链接
	preg_match_all ( '/\[(url)=([http|https|ftp]+:\/\/[a-zA-Z0-9\.\-\?\=\_\&amp;\/\'\`\%\:\@\^\+\,\.]+)\]([^\[]+)(\[\/url\])/is',
	$strcontent, $contenturl);
	foreach($contenturl[2] as $c1)
	{
		$strcontent = str_replace ( "[url={$c1}]", '', $strcontent);
		$strcontent = str_replace ( "[/url]", '', $strcontent);
	}
	//匹配视频
	preg_match_all ( '/\[(视频)(\d+)\]/is', $strcontent, $videos );
	foreach ($videos[2] as $vitem)
	{
		$htmlTpl = '';
		$strcontent = str_replace ( '[视频'.$vitem.']', $htmlTpl, $strcontent );
	}
	return $strcontent;	
}
// ik专用解析输出内容
/**
 * 处理内容文本输出
 * @param string $type     类型
 * @param string $typeid   类型ID
 * @param string $content  文本内容
 * @param boolean $isformat  是否开启格式
 * @return void 纯文本
 */
function ikhtml($type,$typeid,$content,$isformat = '0'){
	//图片
	$arr_photo = array();
	//匹配本地图片
	$strcontent = $content;	
	//是否开启格式化内容
	if($isformat =='1'){
		$strcontent = str_replace(' ', '&nbsp;', $strcontent);
	}
	preg_match_all ( '/\[(图片)(\d+)\]/is', $strcontent, $photos );
	$images_mod = new IKPHP\Common\Models\Images();	
	foreach ($photos [2] as $key=>$item) {
		$strPhoto = $images_mod::getImageByseqid($type,$typeid,$item);
		$htmlTpl = '<div class="img_'.$strPhoto['align'].'">
						<a href="'.$strPhoto['bimg'].'" target="_blank" title="点击查看原图"><img alt="'.$strPhoto['title'].'" src="'.$strPhoto['mimg'].'"  title="点击查看原图"/></a>
						<span class="img_title" >'.$strPhoto['title'].'</span>
					</div><div class="clear"></div>';

		$strcontent = str_replace ( '[图片'.$item.']', $htmlTpl, $strcontent );
	}
	//匹配链接
	preg_match_all ( '/\[(url)=([http|https|ftp]+:\/\/[a-zA-Z0-9\.\-\?\=\_\&amp;\/\'\`\%\:\@\^\+\,\.]+)\]([^\[]+)(\[\/url\])/is',
	$strcontent, $contenturl);
	foreach($contenturl[2] as $c1)
	{
		$strcontent = str_replace ( "[url={$c1}]", '<a href="'.$c1.'" target="_blank">', $strcontent);
		$strcontent = str_replace ( "[/url]", '</a>', $strcontent);
	}
	//匹配视频
	preg_match_all ( '/\[(视频)(\d+)\]/is', $strcontent, $videos );
	foreach ($videos[2] as $vitem)
	{
		//$strVideo =  D('Common/Videos')->getVideoByseqid($type,$typeid,$vitem);;
		//$videohtml = ikVideo($strVideo['videourl'],$strVideo['title']);
		//$strcontent = str_replace ( '[视频'.$vitem.']', $videohtml, $strcontent );
	}

	return $strcontent;
}
function todaytime() {
    return mktime(0, 0, 0, date('m'), date('d'), date('Y'));
}
/**
 * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
 * @param string $name 缓存名称
 * @param mixed $value 缓存值
 * @param string $path 缓存路径
 * @return mixed
 */
function F($name, $value = '', $path='') {
	global $di,$config;
    //Cache data for one day by default
    $frontCache = new \Phalcon\Cache\Frontend\Data($config->cache->modelCache->frontend->options->toArray());
    if(empty($path)){
    	$dir = RUN_PATH_CACHE.'model/';
    }else{
    	$dir = RUN_PATH_CACHE.'model/'.$path.'/';
    }
    if(!is_dir($dir)){
    	mkdir($dir, 0777, true);
    }
    //Memcached connection settings
    $backCache = new \Phalcon\Cache\Backend\File($frontCache,array('cacheDir'=>$dir,'prefix'=>'ik-data-'));
    if ('' !== $value) {
    	if (is_null($value)) {
    		$backCache->delete($name);
    		return;
    	}else{
    		$backCache->save($name, $value);
    		return;
    	}
    }
	$value = $backCache->get($name);
    return $value;
}
//提取关键字
function ikscws($content){return $content;}
//违禁词组过滤
function ikwords($text){return $text;}
/**
 * 处理时间的函数
 * @param int $btime 开始时间
 * @param int $etime 结束时间
 * */
function getTime($btime, $etime) {
	if ($btime < $etime) {
		$stime = $btime;
		$endtime = $etime;
	} else {
		$stime = $etime;
		$endtime = $btime;
	}
	$timec = $endtime - $stime;
	$days = intval ( $timec / 86400 );
	$rtime = $timec % 86400;
	$hours = intval ( $rtime / 3600 );
	$rtime = $rtime % 3600;
	$mins = intval ( $rtime / 60 );
	$secs = $rtime % 60;
	if ($days >= 1) {
		return $days . ' 天前';
	}
	if ($hours >= 1) {
		return $hours . ' 小时前';
	}

	if ($mins >= 1) {
		return $mins . ' 分钟前';
	}
	if ($secs >= 1) {
		return $secs . ' 秒前';
	}else{
		return '刚刚';
	}

}
//初始化 url
function initurl($url) {

	$newurl = '';
	$blanks = array('url'=>'');
	$urls = $blanks;

	if(strlen($url)<10) return $blanks;
	$urls = @parse_url($url);
	if(empty($urls) || !is_array($urls)) return $blanks;
	if(empty($urls['scheme'])) return $blanks;
	if($urls['scheme'] == 'file') return $blanks;

	if(empty($urls['path'])) $urls['path'] = '/';
	$newurl .= $urls['scheme'].'://';
	$newurl .= empty($urls['user'])?'':$urls['user'];
	$newurl .= empty($urls['pass'])?'':':'.$urls['pass'];
	$newurl .= empty($urls['host'])?'':((!empty($urls['user']) || !empty($urls['pass']))?'@':'').$urls['host'];
	$newurl .= empty($urls['port'])?'':':'.$urls['port'];
	$newurl .= empty($urls['path'])?'':$urls['path'];
	$newurl .= empty($urls['query'])?'':'?'.$urls['query'];
	$newurl .= empty($urls['fragment'])?'':'#'.$urls['fragment'];

	$urls['port'] = empty($urls['port'])?'80':$urls['port'];
	$urls['url'] = $newurl;

	return $urls;
}
function strexists($haystack, $needle) {
	return !(strpos($haystack, $needle) === FALSE);
}
//读文件 借用 super site 的方法
function sreadfile($filename, $mode='r', $remote=0, $maxsize=0, $jumpnum=0) {
	if($jumpnum > 5) return '';
	$contents = '';

	if($remote) {
		$httpstas = '';
		$urls = initurl($filename);
		if(empty($urls['url'])) return '';

		$fp = @fsockopen($urls['host'], $urls['port'], $errno, $errstr, 20);
		if($fp) {
			if(!empty($urls['query'])) {
				fputs($fp, "GET $urls[path]?$urls[query] HTTP/1.1\r\n");
			} else {
				fputs($fp, "GET $urls[path] HTTP/1.1\r\n");
			}
			fputs($fp, "Host: $urls[host]\r\n");
			fputs($fp, "Accept: */*\r\n");
			fputs($fp, "Referer: $urls[url]\r\n");
			fputs($fp, "User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)\r\n");
			fputs($fp, "Pragma: no-cache\r\n");
			fputs($fp, "Cache-Control: no-cache\r\n");
			fputs($fp, "Connection: Close\r\n\r\n");

			$httpstas = explode(" ", fgets($fp, 128));
			if($httpstas[1] == 302 || $httpstas[1] == 302) {
				$jumpurl = explode(" ", fgets($fp, 128));
				return sreadfile(trim($jumpurl[1]), 'r', 1, 0, ++$jumpnum);
			} elseif($httpstas[1] != 200) {
				fclose($fp);
				return '';
			}

			$length = 0;
			$size = 1024;
			while (!feof($fp)) {
				$line = trim(fgets($fp, 128));
				$size = $size + 128;
				if(empty($line)) break;
				if(strexists($line, 'Content-Length')) {
					$length = intval(trim(str_replace('Content-Length:', '', $line)));
					if(!empty($maxsize) && $length > $maxsize) {
						fclose($fp);
						return '';
					}
				}
				if(!empty($maxsize) && $size > $maxsize) {
					fclose($fp);
					return '';
				}
			}
			fclose($fp);

			if(@$handle = fopen($urls['url'], $mode)) {
				if(function_exists('stream_get_contents')) {
					$contents = stream_get_contents($handle);
				} else {
					$contents = '';
					while (!feof($handle)) {
						$contents .= fread($handle, 8192);
					}
				}
				fclose($handle);
			} elseif(@$ch = curl_init()) {
				curl_setopt($ch, CURLOPT_URL, $urls['url']);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);//timeout
				$contents = curl_exec($ch);
				curl_close($ch);
			} else {
				//无法远程上传
			}
		}
	} else {
		if(@$handle = fopen($filename, $mode)) {
			$contents = fread($handle, filesize($filename));
			fclose($handle);
		}
	}

	return $contents;
}
//写文件 借用 super site 的方法
function writefile($filename, $writetext, $filemod='text', $openmod='w', $eixt=1) {
	if(!@$fp = fopen($filename, $openmod)) { echo $filename;die;
		if($eixt) {
			exit('File :<br>'.srealpath($filename).'<br>Have no access to write!');
		} else {
			return false;
		}
	} else {
		$text = '';
		if($filemod == 'php') {
			$text = "<?php\r\n\r\nif(!defined('IN_IK')) exit('Access Denied');\r\n\r\n";
		}
		$text .= $writetext;
		if($filemod == 'php') {
			$text .= "\r\n\r\n?>";
		}
		flock($fp, 2);
		fwrite($fp, $text);
		fclose($fp);
		return true;
	}
}
//格式化路径
function srealpath($path) {
	$path = str_replace('./', '', $path);
	if(DIRECTORY_SEPARATOR == '\\') {
		$path = str_replace('/', '\\', $path);
	} elseif(DIRECTORY_SEPARATOR == '/') {
		$path = str_replace('\\', '/', $path);
	}
	return $path;
}
// 获取目录
function getattachdir($dirpatharr) {
	$dirs = C('ik_attach_path');
	$subarr = array();
	$dirarr = explode('/', $dirpatharr);
	foreach ($dirarr as $value) {
		$dirs .= '/'.$value;
		if(smkdir($dirs)) {
			$subarr[] = $value;
		} else {
			break;
		}
	}
	return implode('/', $subarr);
}
// 生成目录
function smkdir($dirname, $ismkindex=1) {
	$mkdir = false;
	if(!is_dir($dirname)) {
		if(@mkdir($dirname, 0777)) {
			if($ismkindex) {
				@fclose(@fopen($dirname.'/index.htm', 'w'));
			}
			$mkdir = true;
		}
	} else {
		$mkdir = true;
	}
	return $mkdir;
}